/// <reference types="chrome"/>

interface SubtitleMessage {
  type: 'SUBTITLE_UPDATE';
  subtitle: string;
}

interface SubtitleData {
  text: string;
  timestamp: number;
  videoTime: number;
}

class SubtitleObserver {
  private observer: MutationObserver | null = null;
  private subtitleContainer: Element | null = null;
  private lastSubtitle: string = '';

  constructor() {
    this.init();
  }

  private init() {
    // 等待视频播放器加载
    this.waitForPlayer();
  }

  private waitForPlayer() {
    const checkInterval = setInterval(() => {
      // B站视频字幕容器的选择器
      const container = document.querySelector('.bpx-player-subtitle-panel');
      if (container) {
        clearInterval(checkInterval);
        this.subtitleContainer = container;
        this.startObserving();
      }
    }, 1000);
  }

  private startObserving() {
    if (!this.subtitleContainer) return;

    this.observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList' || mutation.type === 'characterData') {
          this.handleSubtitleChange();
        }
      });
    });

    this.observer.observe(this.subtitleContainer, {
      childList: true,
      subtree: true,
      characterData: true
    });
  }

  private handleSubtitleChange() {
    if (!this.subtitleContainer) return;

    const subtitleElement = this.subtitleContainer.querySelector('.bpx-player-subtitle-panel-text');
    if (!subtitleElement) return;

    const currentText = subtitleElement.textContent?.trim() || '';
    
    // 避免重复发送相同的字幕
    if (currentText && currentText !== this.lastSubtitle) {
      this.lastSubtitle = currentText;
      this.sendSubtitleData(currentText);
    }
  }

  private getCurrentVideoTime(): number {
    const video = document.querySelector('video');
    return video ? video.currentTime : 0;
  }

  private sendSubtitleData(text: string) {
    const subtitleData: SubtitleData = {
      text,
      timestamp: Date.now(),
      videoTime: this.getCurrentVideoTime()
    };

    // 发送消息到后台脚本
    chrome.runtime.sendMessage({
      type: 'NEW_SUBTITLE',
      data: subtitleData
    });
  }

  public destroy() {
    if (this.observer) {
      this.observer.disconnect();
      this.observer = null;
    }
  }
}

// 启动字幕观察器
const subtitleObserver = new SubtitleObserver();

// 监听页面卸载事件
window.addEventListener('unload', () => {
  subtitleObserver.destroy();
});

// 监听视频播放器加载
function observeVideoPlayer() {
  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.addedNodes.length) {
        const videoPlayer = document.querySelector('.bilibili-player-video');
        if (videoPlayer) {
          // 找到视频播放器，开始监听字幕
          startSubtitleObserver();
          observer.disconnect();
          break;
        }
      }
    }
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true
  });
}

// 监听字幕变化
function startSubtitleObserver() {
  const subtitleObserver = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type === 'childList') {
        const subtitleElement = document.querySelector('.bilibili-player-video-subtitle');
        if (subtitleElement) {
          const subtitleText = subtitleElement.textContent;
          if (subtitleText) {
            // 发送字幕到 background script 处理
            const message: SubtitleMessage = {
              type: 'SUBTITLE_UPDATE',
              subtitle: subtitleText
            };
            chrome.runtime.sendMessage(message);
          }
        }
      }
    }
  });

  const subtitleContainer = document.querySelector('.bilibili-player-video-subtitle');
  if (subtitleContainer) {
    subtitleObserver.observe(subtitleContainer, {
      childList: true,
      characterData: true,
      subtree: true
    });
  }
}

// 初始化
function init() {
  // 检查是否在视频页面
  if (window.location.href.includes('bilibili.com/video/')) {
    observeVideoPlayer();
  }
}

// 启动脚本
init();

// 监听来自侧边栏的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'SEEK_VIDEO') {
    const video = document.querySelector('video');
    if (video) {
      video.currentTime = message.time;
    }
  }
}); 